import { computed, type ComputedRef } from 'vue';

/**
 * 创建带参数缓存的 computed 函数
 * @param fn 原始计算函数（支持任意参数、任意返回值）
 * @returns 带缓存的函数，相同参数会返回同一个 ComputedRef 实例
 */
export function useComputed<T extends any[], R>(
	fn: (...args: T) => R
): (...args: T) => ComputedRef<R> {
	const cacheMap = new Map<string, ComputedRef<R>>();

	return function (...args: T): ComputedRef<R> {
		const cacheKey = JSON.stringify(args);

		if (cacheMap.has(cacheKey)) {
			return cacheMap.get(cacheKey)!;
		}
		const computedResult = computed(() => fn(...args));
		cacheMap.set(cacheKey, computedResult);
		return computedResult;
	};
}
